package com.zh.test.fastdfs;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadFileWriter;
import com.github.tobato.fastdfs.domain.upload.FastFile;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.zh.test.bean.Person;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Optional;


/**
 * @Author zh
 * @Description 测试client客户端 https://www.cnblogs.com/yiyezhiqiuwuchen/p/13579748.html
 * @Date 2020/9/1
 * @Param
 * @return
 **/
@Component
@Slf4j
public class fastdfsUtil {
    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * @return filepath 文件存放路径
     * @Author zh
     * @Description 上传文件 by  filepath
     * @Date 2020/9/2
     * @Param inputstream  文件字节流
     **/
    public String upload(String oldFilePath) {
        log.info("上传文件路径:{}", oldFilePath);
        StorePath storePath = null;
        try {
            File file = new File(oldFilePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            FastImageFile fastImageFile = new FastImageFile.Builder().withFile(fileInputStream,
                    file.length(), file.getName().split("\\.")[1]).build();
            storePath = storageClient.uploadImage(fastImageFile);
        } catch (FileNotFoundException e) {
            log.error("错误,文件上传失败{}", oldFilePath);
            e.printStackTrace();

        }
        return Optional.ofNullable(storePath).map(s -> s.getFullPath()).orElse(null);
    }

    /**
     * @return 文件存放路径
     * @Author zh
     * @Description 上传文件 by  MultipartFile
     * @Date 2020/9/1
     * @Param MultipartFile(spring提供文件容器)
     **/
    public String upload(MultipartFile multipartFile) throws Exception {
        log.info("MultipartFile上传文件信息:文件名称:{},文件大小{}", multipartFile.getOriginalFilename(), multipartFile.getSize());
        FastImageFile fastImageFile = new FastImageFile.Builder().withFile(multipartFile.getInputStream(),
                multipartFile.getSize(), multipartFile.getOriginalFilename().split("\\.")[1]).build();
        StorePath storePath = storageClient.uploadImage(fastImageFile);
        log.info("上传文件路径:{}", storePath.getFullPath());
        storePath = Optional.ofNullable(storePath).orElse(new StorePath());
        return storePath.getFullPath();
    }


    /**
     * @return
     * @Author zh
     * @Description 删除文件
     * @Date 2020/9/1
     * @Param 文件路径   /groupName/磁盘路径/磁盘路径/文件名
     **/
    public boolean deleteFile(String filePath) {
        Assert.notNull(filePath, "文件路径不能为空");
        StorePath storePath = StorePath.parseFromUrl(filePath);
        try {
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            return true;
        } catch (Exception e) {
            log.error("文件删除失败:{}", filePath);
            return false;
        }
    }

    /**
     * @return
     * @Author zh
     * @Description 直接下载文件到流
     * @Date 2020/9/1
     * @Param filePath 需要下载的文件路径  fileName 生成的文件名
     **/
    public void downFile(String filePath, String fileName) {
        Assert.notNull(filePath, "服务器端文件路径不能为空");
        StorePath storePath = StorePath.parseFromUrl(filePath);
        fileName = Optional.ofNullable(fileName).orElse(storePath.getPath());
        downFile(storePath, fileName, null);
    }

    /**
     * @return
     * @Author zh
     * @Description 下载文件到指定路径
     * @Date 2020/9/1
     * @Param filePath 需要下载的文件路径  fileName 生成的文件名  newFilePath 下载的文件存放的路径
     **/
    public void downFile(String filePath, String fileName, String newFilePath) {
        Assert.notNull(filePath, "服务器端文件路径不能为空");
        StorePath storePath = StorePath.parseFromUrl(filePath);
        fileName = Optional.ofNullable(fileName).orElse(storePath.getPath());
        downFile(storePath, fileName, newFilePath);
    }

    // 基础下载方法
    public void downFile(StorePath storePath, String fileName, String newFilePath) {
        try {
            if (!StringUtils.isEmpty(newFilePath)) {
                storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadFileWriter(fileName));
            } else {
                storageClient.downloadFile(storePath.getGroup(), storePath.getPath(),
                        (InputStream ins) -> {
                            FileUtils.copyInputStreamToFile(ins, new File(newFilePath));
                            return null;
                        }
                );
            }
        } catch (Exception e) {
            log.error("错误,文件下载失败");
        }

    }

    /**
     * @Author zh
     * @Description 批量删除
     * @Date 2020/9/1
     * @Param
     * @return
     **/
    /**
     * @return
     * @Author zh
     * @Description 批量上传
     * @Date 2020/9/1
     * @Param
     **/
    public static void main(String[] args) {
        File file = new File("D:\\company\\lesu\\MapAndStream.png");
        file.getName();
        Person person = new Person().setSex("man");
        Person person2 = null;
        String s = Optional.ofNullable(person).map(p -> p.getSex()).orElse(null);
        String sss = Optional.ofNullable(person2).map(p -> p.getSex()).orElse("sss");
    }
}
